<script setup lang="ts">
import { useWatcher } from '@sa/alova/client';
import { ref, watch } from 'vue';
import { alova } from '@/service/request';

defineOptions({
  name: 'PorDictRadio'
});

interface Props {
  dictCode?: string;
  valueToNumber?: boolean;
  valueToBool?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  dictCode: undefined,
  valueToNumber: false,
  valueToBool: false
});

const emit = defineEmits<{
  /** 绑定的数据 */
  'update:value': [value: Array<string | number>];
}>();

const dynamicOptions = ref<Array<any>>([]);

const dictItems = (dictCode: string | undefined) => {
  return alova.Get<Record<string, any>[]>(`/setting/dictItem/simpleList`, { params: { dictCode } });
};

const dictCode = ref(props.dictCode || '');
watch(
  () => props.dictCode,
  (newDictCode: string | undefined) => {
    dictCode.value = newDictCode || '';
  }
);

const { loading } = useWatcher(
  // 必须设置为返回method实例的函数
  () => dictItems(dictCode.value),
  [dictCode],
  {
    immediate: true
  }
).onSuccess(({ data }) => {
  if (props.valueToNumber) {
    data.forEach((item: any) => {
      const value = item.value;
      item.value = Number(value);
    });
  }

  if (props.valueToBool) {
    data.forEach((item: any) => {
      const value = item.value;

      // eslint-disable-next-line no-nested-ternary
      item.value = value === 'true' ? true : value === 'false' ? false : Boolean(value);
    });
  }

  dynamicOptions.value = data;
});

function onValueChange(v: any) {
  emit('update:value', v);
}
</script>

<template>
  <NRadioGroup @update:value="onValueChange">
    <NRadio
      v-for="item in dynamicOptions"
      :key="item.value"
      :value="item.value"
      :label="item.name"
      :loading="loading"
    />
  </NRadioGroup>
</template>

<style scoped></style>
